package com.hzw.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.hzw.dto.BookExcelDto;
import com.hzw.model.Book;
import com.hzw.sevice.BookService;
import com.hzw.vo.BookExcelVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("book")
public class BookController {
    private final static Logger logger = LoggerFactory.getLogger(BookController.class);


    @Autowired
    private BookService bookService;


    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        String [] head={"书名", "价格", "描述", "创建时间"};
        List<Book> bookList = bookService.list();
        //代表一个Excel工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        //代表Excel工作簿中的一个工作表
        XSSFSheet sheet = workbook.createSheet();
       // sheet.setDefaultColumnWidth((short)18);
        sheet.setColumnWidth(0, 20 * 256); // 设置第一列的宽度为20个字符的宽度
        sheet.setColumnWidth(1, 15 * 256); // 设置第二列的宽度为15个字符的宽度
        sheet.setColumnWidth(2, 35 * 256); // 设置第三列的宽度为35个字符的宽度
        sheet.setColumnWidth(3, 20 * 256); // 设置第四列的宽度为20个字符的宽度
        // 创建CellStyle对象并设置其属性
        XSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        //代表Excel工作表中的一行
         Row row = sheet.createRow(0);
        // 遍历每个单元格并应用CellStyle对象
        for (int i = 0; i <head.length ; i++) {
            //代表Excel工作表中的单元格
            Cell cell = row.createCell(i);
            cell.setCellType(CellType.STRING);
            //在head数组中对应位置的值设置为该单元格的值
            cell.setCellValue(head[i]);
            cell.setCellStyle(style);
        }
        int size=bookList.size();
        if (size==0){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            String fileName = URLEncoder.encode("书籍导出", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + fileName + ".xlsx");
            response.flushBuffer();
            workbook.write(response.getOutputStream());
        }
        for (int i = 0; i <size ; i++) {
            //代表Excel工作表中的一行
            Row row1 = sheet.createRow(i+1);
            if (i >= bookList.size()) {
                break;
            }
            System.out.println("bookList.size() = " + bookList.size());
            Book book = bookList.get(i );
            //cell代表每一列
            Cell cell = row1.createCell(0);
            cell.setCellStyle(style);
            cell.setCellValue(book.getName());
            Cell cell1 = row1.createCell(1);
            cell1.setCellStyle(style);
            cell1.setCellValue(book.getPrice());
            Cell cell2 = row1.createCell(2);
            String description = book.getDescription();
            if (StringUtils.isBlank(description)){
                description="未填入描述";
            }
            cell2.setCellStyle(style);
            cell2.setCellValue(description);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = simpleDateFormat.format(book.getCreateTime());
            Cell cell3 = row1.createCell(3);
            cell3.setCellValue(date);

        }
        //将Excel文件作为响应内容发送给客户端
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String fileName = URLEncoder.encode("书籍导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + fileName + ".xlsx");
       //强制刷新响应输出缓存区，确保所有响应内容都写出到网络流中
        response.flushBuffer();
        //将Excel文件）写入响应的输出流中
        workbook.write(response.getOutputStream());

    }

    @GetMapping("/exportAnnotation")
    public void exportAnnotation(HttpServletResponse response) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            String fileName = URLEncoder.encode("书籍导出", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + fileName + ".xlsx");
            List<Book> list = bookService.list();
            ArrayList<BookExcelVo> voList = new ArrayList<>();
            list.forEach(projectManager -> {
                BookExcelVo bookExcelVo = new BookExcelVo();
                BeanUtils.copyProperties(projectManager,bookExcelVo);
                voList.add(bookExcelVo);
            });
            // 内容的策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            //自动换行
            contentWriteCellStyle.setWrapped(true);
            //设置上下居中
            contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
            ExcelWriterBuilder write = EasyExcel.write(response.getOutputStream(), BookExcelVo.class);
            write.registerWriteHandler(horizontalCellStyleStrategy).sheet("sheet0")
                    .doWrite(voList);

        } catch (Exception e) {
            logger.error("导出失败：{}", e.getMessage());
        }}
    /**
     * TODO 导入
     * @param file:
     */
    @PostMapping("/importBook")
    public void importEquip(@RequestBody MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(file.getOriginalFilename().lastIndexOf(".") + 1);

        if (!("xlsx".equals(suffixName) || "XLSX".equals(suffixName) || "xls".equals(suffixName) || "XLS".equals(suffixName))) {
         throw new Exception("文件格式错误");
        }
        List<BookExcelDto> equipmentExcelDtoList = EasyExcel.read(file.getInputStream()).head(BookExcelDto.class).sheet().doReadSync();
        ArrayList<Book> books = new ArrayList<>();
        for (BookExcelDto bookExcelDto : equipmentExcelDtoList) {
            Book book = new Book();
            BeanUtils.copyProperties(bookExcelDto,book);
            books.add(book);
        }
        bookService.saveBatch(books);
        logger.info("读取到bookList数据data:" + JSON.toJSONString(equipmentExcelDtoList));
        //处理读取到的数据
    }

    @GetMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response) throws IOException {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            String fileName = URLEncoder.encode("书籍标准模板", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + fileName + ".xlsx");

                List<BookExcelVo> list = new ArrayList<>();
                BookExcelVo bookExcelVo = new BookExcelVo();
            Book book = bookService.getById(1);
            bookExcelVo.setType(book.getType());
                bookExcelVo.setDescription(book.getDescription());
                bookExcelVo.setCreateTime(book.getCreateTime());
                bookExcelVo.setPrice(book.getPrice());
                bookExcelVo.setName(book.getName());
                list.add(bookExcelVo);
                EasyExcel.write(response.getOutputStream(), BookExcelVo.class).sheet(  "书籍导入模板").doWrite(list);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
            logger.error("下载模板失败：{}", e.getMessage());
        }
    }

    @GetMapping("groupByBook")
    public  Map<Long, List<Book>> groupByBook(){
        List<Book> list = bookService.list();
        HashMap<Long, List<Book>> longListHashMap = list.stream().collect(Collectors.groupingBy(Book::getParentId, HashMap::new, Collectors.toList()));

        Map<Long, List<Book>> ListHashMap = list.stream().collect(Collectors.groupingBy(book -> book.getParentId()));
        System.out.println(longListHashMap);
        return ListHashMap;

    }



}
